function isArray(val){
  return Object.prototype.toString.call(val) === '[object Array]';
}

function isObject(val){
  return typeof val === 'object' && val!==null;
}

function deepCopy(obj2){
  /**
   * 把一个对象递归拷贝给另外一个对象
   * 源对象和拷贝后的对象没有引用关系
   */
  var obj = isArray(obj2)?[]:{};
  for (const property in obj2) {
    //如果当前拷贝数据还是一个对象的话，那就继续调用deepCopy进行二次拷贝
    if (isObject(obj2[property])) {
      obj[property] = deepCopy(obj2[property]);
    }else{
      obj[property] = obj2[property];
    }
  }
  return obj;
}

// let a={a:2,b:2,arr:[1,2,3]};
// let b ={c:3,d:4,arr:[4,5,6]};
// let c = deepMerge(a,b);
// console.log(c);

//合并对象，不是拷贝
function deepMerge(obj1,obj2){
  var obj = deepCopy(obj1);

  for (var property in obj2) {
    var val = obj[property];
    var val2 = obj2[property];
    if (isObject(val) && isObject(val2)) {
      obj[property] = deepMerge(val,val2);
    }else if(isObject(val2)){
      obj[property] =deepCopy(val2);
    }else{
      obj[property] = val2;
    }
  }

  return obj;
}

function mergeConfig(config1,config2){

  //深拷贝
  /**
   * 注意：不能直接把config2合并到config1
   * 把config1先通过深拷贝赋值给一个新的对象
   */
  var config = deepCopy(config1);
  
  var properties1 = ['url','method','params','data'];
  //把config2合并到config
  for (const property in config2) {
    //针对一些没有必要合并的配置直接赋值
    if(properties1.indexOf(property) !=-1){
      config[property] = config2[property];
    }else{
      if(isObject(config2[property])){
        config[property] =deepMerge[config[property],config2[property]];
      }else{
        config[property] = config2[property];
      }
    }
  }
  return config;
} 

export default {
  mergeConfig,
  deepCopy,
  isObject,
  isArray,
  deepMerge
}